import { ExpertAppointmentTimesProps, ExpertProps } from '@/api/expert';
import { OrderCancel, OrderDetail } from '@/api/order';
import { Button, Divider, Icon, Popup } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';
import CutDown from './CutDown';

export default function useReservationDetail(props: {
  detail: ExpertProps;
  onFinish: Function; //倒计时结束
}) {
  const [show, setShow] = useState<boolean>(false);

  //订单详情
  const { data } = useRequest(
    () => OrderDetail({ id: props.detail?.partin_id }),
    {
      ready: Boolean(props.detail?.partin_id),
      cacheKey: 'order:detail',
    }
  );

  //取消预约
  const { runAsync: runCancelAsync, loading } = useRequest(OrderCancel, {
    manual: true,
  });

  //计算用户已选择的
  const selectedDatas = useMemo(
    () =>
      data?.time_data
        ?.map((item) => item.list)
        .flat(Infinity) as ExpertAppointmentTimesProps['list'],
    [data]
  );

  function renderNode() {
    return (
      <Popup
        show={show}
        position='bottom'
        round
        onClose={() => setShow(false)}
        style={{
          overflow: 'initial',
        }}
      >
        <Icon
          name='close'
          className=' text-3xl text-white absolute right-4 -top-[90px]'
          onClick={() => setShow(false)}
        />
        <View className='px-4 py-3 text-lg font-bold block'>预约详情</View>
        <Divider className='m-0' />
        <View className='p-4'>
          {/* <Text className='block text-sm text-black font-bold mb-2'>
            已选日期
          </Text>

          {data?.time_data?.map((item) => (
            <View className='border-4 border-primary rounded-lg text-primary bg-[#EFF3FA] px-4 py-2 text-center inline-block mr-2'>
              <Text>{item.week}</Text>
              <Text className=' block font-bold'>{item.date}</Text>
            </View>
          ))} */}

          <View className='flex leading-none items-center mb-2'>
            <Text className='block text-sm text-black font-bold '>
              已选时段
            </Text>
            <Text className=' text-xs text-gary3 block'>
              （最多选择3个时段，专家将通过其中之一）
            </Text>
          </View>
          {selectedDatas?.map((item) => (
            <View className='border-4 border-primary rounded-lg flex text-primary bg-[#EFF3FA] py-2 px-2 mb-1'>
              <Text>
                {dayjs(item.am_date).format('MM-DD')} {item.start_time} -
                {item.end_time}
              </Text>
              <Text className=' block truncate flex-1 ml-2 text-right'>
                {item.address}
              </Text>
            </View>
          ))}

          {/* 预约备注 */}
          {data?.remark && (
            <>
              <Text className='block text-sm text-black font-bold mt-6 mb-2'>
                预约备注
              </Text>
              <View className=' px-4 py-2 bg-gary2 text-xs rounded-lg'>
                {data?.remark}
              </View>
            </>
          )}

          <Text className='block text-sm text-black font-bold mt-6'>
            预约状态
          </Text>
          {data?.left_time && (
            <CutDown
              value={data?.left_time}
              onFinish={() => props.onFinish()}
            />
          )}
        </View>

        <Text className=' text-xs text-center text-gary3 block mb-2'>
          专家确认前您可以无责取消
        </Text>
        <View className='px-4'>
          <Button
            loading={loading}
            block
            className='bg-gary3 text-white'
            onClick={async () => {
              if (!props.detail?.partin_id) return;
              Taro.showModal({
                title: '取消预约',
                content: `您确定要取消预约吗？专家确认前您可以无责取消, `,
                success: async ({ confirm }) => {
                  if (!confirm) return;
                  await runCancelAsync({
                    id: props.detail?.partin_id,
                  });

                  Taro.showToast({
                    title: '已取消',
                    icon: 'success',
                  });

                  props.onFinish();
                  setShow(false);
                },
              });
            }}
          >
            取消预约
          </Button>
        </View>
      </Popup>
    );
  }

  return {
    renderNode,
    open: () => setShow(true),
  };
}
